<template>
  <div>
    <el-card class="search-card">
      <basic-table-form
        ref="formData"
        isScalingBtn
        :formColumns="formItemList"
        :dataSource="formData"
        :defaultExpandStatus="false"
        :handleSearchForm="handleQueryForm"
        @getFormData="getFormData"
      >
        <el-row slot="extensionActions" type="flex">
          <el-button
            v-if="showBtn('批量维护')"
            type="primary"
            @click="batchDialogVisble = true"
          >批量维护</el-button>
        </el-row>
      </basic-table-form>
    </el-card>
    <el-card class="table-card">
      <basic-table
        showActionCol
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :pagination="pagination"
        :pageSizes="pageSizes"
        :tableHeight="460"
        :actionRender="renderTableBtnAction"
        :selectionChange="handleSelectionChange"
        @pageChange="handlePageChange"
        @pageSizeChange="handlePageSizeChange"
      >
        <div slot="content_context">
          <el-button
            v-if="showBtn('批量提交')"
            :loading="btnLoading.batchSubmit"
            type="primary"
            size="mini"
            icon="el-icon-upload2"
            :disabled="tableInfo.selection.length == 0"
            @click="handleSubmit"
            >批量提交</el-button
          >
        </div>
      </basic-table>
    </el-card>
    <batch-maintain-dialog :visible.sync="batchDialogVisble" />
  </div>
</template>
<script>
import BasicTableForm from '@/components/BasicForm';
import BasicTable from '@/components/BasicTable';
import {
  FORM_ITEM_LIST,
  initTableColumns,
} from '../constants/adding';
import batchMaintainDialog from '@/components/common/dialog/batchMaintainDialog';
import { setAuthBtnId } from '@/utils/bizUtils';
import { getSearchParamBySearchType, getInitFormData } from '@/utils/getUtils';
import {
  getNoPerfectGoodsListService,
  deleteNotPerfectGoodsService,
  batchSubmitGoodsService
} from '@/api/commodity/commodityAccessManage/commodityToPerfect';
import basePage from '@/mixins/commodity/basePage';
import { judgeAuthDepartmentFn } from '@/pages/commodity/modules/utils';

export default {
  mixins: [basePage],
  components: {
    batchMaintainDialog,
    BasicTableForm,
    BasicTable
  },
  data () {
    return {
      formItemList: FORM_ITEM_LIST,
      tableInfo: {
        list: [],
        columns: initTableColumns(this),
        loading: false,
        selection: []
      },
      batchDialogVisble: false,
      productUuid: '',
      formData: getInitFormData(FORM_ITEM_LIST),
      btnLoading: {
        batchSubmit: false, // 批量提交按钮loading
      }
    };
  },
  created () {
    this.handleQueryForm();
  },
  methods: {
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      return <div class="table-action"><el-button type="text" onClick={() => this.handleDeleteRow(row)}>删除</el-button></div>;
    },
    // 获取查询入参
    getSearchParams () {
      const data = {
        searchParam: JSON.stringify([
          ...getSearchParamBySearchType(FORM_ITEM_LIST, this.formData),
          { name: 'belongToDepartmentFlag', value: '1' }, // 查询归属部门
          { name: 'groupFlag', value: '1' } // 是否是集团总部 0:不是 1:是
        ]),
        ...this.pagination
      }
      return data;
    },
    // 获取表格数据
    async getTableData () {
      const data = this.getSearchParams();
      const loadingFn = state => { this.tableInfo.loading = state }
      setAuthBtnId('查询')
      const res = await getNoPerfectGoodsListService(data, loadingFn)
      if (res?.retData) {
        const { results, totalNum } = res.retData
        this.tableInfo.list = (results ?? []).map(item => ({
          ...item,
          productUuid: item.addStateDTO?.productUuid ?? ''
        }));
        this.pagination.totalNum = totalNum;
      }
    },
    // 表格勾选
    handleSelectionChange (list) {
      this.tableInfo.selection = list;
    },
    // 跳转详情
    handleJumpNewPage (name, row, state, stateStr) {
      const notJumpStateList = ['AUDITING', 'OK', 'FAIL'];
      if (notJumpStateList.includes(state)) {
        return;
      }
      switch (name) {
        case 'structureInfoAddState': // 架构信息
          this.handleOpenNewPage({
            name: 'schemaInfoToWait',
            query: { productUuid: row.productUuid, type: 'toWait' }
          });
          break;
        case 'basicInfoAddState': // 商品基本信息
          this.handleOpenNewPage({
            path: '/commodity/commodityAccessManage/waitAccess/jibenxinxi',
            query: { productUuid: row.productUuid }
          });
          break;
        case 'manageAddState': // 商品管理信息
          this.handleOpenNewPage({
            path: '/commodity/commodityAccessManage/waitAccess/information',
            query: { productUuid: row.productUuid }
          });
          break;
        case 'packageAddState': // 商品SKU(包装)信息
          this.handleOpenNewPage({
            path: '/commodity/commodityAccessManage/waitAccess/skuInformation',
            query: { productUuid: row.productUuid }
          });
          break;
        case 'supplyGoodsAddState': // 供货信息
          this.handleOpenNewPage({
            path: '/commodity/commodityAccessManage/waitAccess/gonghuoxinxi',
            query: { productUuid: row.productUuid, state: stateStr }
          });
          break;
        case 'salePriceAddState': // 售价信息
          if (row.addStateDTO && row.addStateDTO.supplyGoodsAddState === 'ADD_OK') {
            this.handleOpenNewPage({
              name: 'toBePerfectSpuSalePrice',
              query: { productUuid: row.productUuid, state: stateStr }
            });
          } else {
            return this.$Message.error('确保供货信息已完善');
          }
          break;
        case 'picAddState': // 图文信息
          this.handleOpenNewPage({
            path: '/commodity/commodityAccessManage/waitAccess/tuwenjieshao',
            query: { productUuid: row.productUuid, spuNo: row.spuNo, productName: row.productNameFinal }
          });
          break;
        case 'acceptanceAddState': // 验收标准
          this.handleAcceptanceTip(row)
          break;
        case 'qualificationAddState': // 资质信息
          this.handleOpenNewPage({
            path: '/commodity/commodityAccessManage/waitAccess/zizhixinxi',
            query: { productUuid: row.productUuid }
          });
          break;
      }
    },
    handleOpenNewPage (data) {
      const { href } = this.$router.resolve(data);
      window.open(href, '_blank');
    },
    // 点击待完善验收标准提示
    handleAcceptanceTip (row) {
      this.$router.push({ name: 'batchAddAcceptanceStandard', query: { spuNo: row.spuNo } })
    },
    // 格式化link type
    formatLinkType (type) {
      let linkType = 'info';
      switch (type) {
        case 'INIT': // 待完善
          linkType = 'primary';
          break;
        case 'ADDING': // 完善中
          linkType = 'primary';
          break;
        case 'FAIL': // 审核驳回
          linkType = 'danger';
          break;
        case 'ADD_OK': // 已完善
          linkType = 'success';
          break;
        case 'AUDITING': // 审核中
          linkType = 'info';
          break;
        case 'OK': // 已完成
          linkType = 'info';
          break;
      }
      return linkType;
    },
    // 删除商品
    handleDeleteRow (row) {
      this.$confirm(
        '删除后将把该商品的所有完善信息删除，您确认吗？',
        { title: '删除', type: 'warning' }
      ).then(() => {
        this.deleteGoods(row.productUuid);
      }).catch(() => {});
    },
    // 删除商品请求
    async deleteGoods (data) {
      const loadingFn = state => { this.tableInfo.loading = state };
      const res = await deleteNotPerfectGoodsService(data, loadingFn);
      if (res) {
        this.$message.success('删除成功');
        this.getTableData();
      }
    },
    // 批量提交
    handleSubmit () {
      const canSubmit = judgeAuthDepartmentFn(this.tableInfo.selection); // 验归属部门方法
      if (!canSubmit) return;
      const productUuids = this.tableInfo.selection.map(item => item.uuid).join(',');
      this.$confirm(
        '确认提交吗？',
        { title: '提交', type: 'warning' }
      ).then(() => {
        this.batchSubmitGoods({ productUuids });
      }).catch(() => {});
    },
    // 批量提交请求
    async batchSubmitGoods (data) {
      setAuthBtnId('批量提交');
      const loadingFn = state => { this.btnLoading.batchSubmit = state };
      const res = await batchSubmitGoodsService(data, loadingFn);
      if (res) {
        this.$message.success('批量提交成功');
        this.getTableData();
      }
    }
  }
};
</script>
